﻿
using System;
using System.Threading;
using System.Text;

namespace NMbsDuplex.TCPServerX.Net.AsyncPool
{
    interface IManagedThreadPool
    {
        string InterfaceVersion { get; }
        Tuple<int, int> ThreadsCapacity();
        Int32 WorkItemWithPThreadID(callBackFunc lambda, ref object objParameter);
    }

    public delegate void callBackFunc(object paramObj);

    public class MyThreadPool : IManagedThreadPool
    {
        public bool isJobsDone = false;

        public string InterfaceVersion
        {
            get
            {
                return "/DrdimsWork/SaaS/API/V1/ThreadPool/0/0/0/1123";
            }
        }
        /// <summary>
        /// 返回当前CPU核心下可供使用的所有线程数和最大工作线程数
        /// </summary>
        /// <returns>元祖 包含2个整形 </returns>
        public Tuple<int, int> ThreadsCapacity()
        {
            int All, Max;
            ThreadPool.GetAvailableThreads(out All, out Max);
            return new Tuple<int, int>(All, Max);
        }

        #region working with ThreadPool
        /// <summary>
        /// 循环回调器 监控一个原子变量 布尔类型 外部设置布尔为false则停止循环线程派生
        /// </summary>
        /// <param name="lambda"></param>
        /// <param name="objParameter"></param>
        /// <returns></returns>
        public int WorkItemWithPThreadID(callBackFunc lambda, ref object objParameter)
        {
            //从工作线程池申请后台线程 执行传入回调
            int availableSizeThread = ThreadsCapacity().Item2;

            // 观察一个 多线程[原子]变量
            Mutex MLock = new Mutex(false, "互斥锁", out isJobsDone);
            while (isJobsDone)
            {
                if (MLock.WaitOne())
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(lambda), objParameter);
                    Thread.Sleep(30);
                }
            }
            return Thread.CurrentThread.ManagedThreadId;
        }
        #endregion
    }
}
